package com.kscrm.web.controller.system;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.kscrm.common.core.domain.R;
import com.kscrm.common.utils.DateUtils;
import com.kscrm.common.utils.SecurityUtils;
import com.kscrm.web.criteria.ChannelCountCriteria;
import com.kscrm.web.criteria.ClientCountCriteria;
import com.kscrm.web.criteria.ProjectCountCriteria;
import com.kscrm.web.criteria.StatSumCriteria;
import com.kscrm.web.enums.ChannelEnum;
import com.kscrm.web.enums.ClientEnum;
import com.kscrm.web.enums.ProjectEnum;
import com.kscrm.web.service.*;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.kscrm.common.config.KsCrnConfig;
import com.kscrm.common.utils.StringUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.kscrm.common.utils.DateUtils.YYYY_MM;
import static com.kscrm.common.utils.DateUtils.dateTimeNow;

/**
 * 首页
 *
 * @author Dhq
 */
@RestController
public class SysIndexController {
    /**
     * 系统基础配置
     */
    @Resource
    private KsCrnConfig ksCrnConfig;

    @Resource
    private IStatService statService;

    @Resource
    private IClientService clientService;
    @Resource
    private IChannelService channelService;

    @Resource
    private IProjectService projectService;

    @Resource
    private IProjectCollectionService projectCollectionService;

    private static final String[] dateArr = new String[]{"今日","本月", "上月", "近两个月", "近三个月", "近半年"};

    /**
     * 访问首页，提示语
     */
    @RequestMapping("/")
    public String index() {
        return StringUtils.format("{}后台管理框架，当前版本：v{}，请通过前端地址访问。", ksCrnConfig.getName(), ksCrnConfig.getVersion());
    }

    /**
     * 控制台数据
     *
     * @return
     */
    @GetMapping("/IndexData")
    public R<Map<String, Object>> indexData() {
        Long userId = SecurityUtils.getUserId();
        // 渠道ID
        Long channelId = SecurityUtils.getChannelId();
        Map<String, Object> data = new HashMap<>();
        Map<String, Object> moneyData = new HashMap<>();
        Map<String, Object> clientData = new HashMap<>();
        Map<String, Object> projectData = new HashMap<>();
        Map<String, Object> channelData = new HashMap<>();

        // 业绩数据
        moneyData.put("收款金额", projectCollectionService.sumProjectMoney(new ProjectCountCriteria().setChannelId(channelId)));
        moneyData.put("签约金额", projectService.sumProjectMoney(new ProjectCountCriteria().setChannelId(channelId)));
        moneyData.put("本月", projectCollectionService.sumProjectMoney(new ProjectCountCriteria().setChannelId(channelId).setDate(dateTimeNow(YYYY_MM))));
        moneyData.put("上月", projectCollectionService.sumProjectMoney(new ProjectCountCriteria().setChannelId(channelId).setDate(DateUtil.format(DateUtil.offsetMonth(new Date(), -1), YYYY_MM))));
        data.put("业绩数据", moneyData);

        // 客户数据
        clientData.put("全部", clientService.selectClientCount(new ClientCountCriteria().setUserId(userId)));
        for (String dateType : dateArr) {
            clientData.put(dateType, getClientData(userId,channelId, dateType));
        }
        data.put("客户数据", clientData);
        // 项目数据
        projectData.put("全部", projectService.selectProjectCount(new ProjectCountCriteria().setChannelId(channelId)));
        for (String dateType : dateArr) {
            projectData.put(dateType, getProjectData(channelId, dateType));
        }
        data.put("项目数据", projectData);
        // 下级渠道数据
        channelData.put("全部", channelService.selectChannelCount(new ChannelCountCriteria().setParentId(channelId)));
        for (String dateType : dateArr) {
            channelData.put(dateType, getChannelData(channelId, dateType));
        }
        data.put("下级渠道", channelData);
        // 更新时间
        data.put("Date", DateUtil.format(DateUtil.offsetHour(DateUtil.date(), -1), "yyyy-MM-dd HH:mm")) ;
        return R.ok(data);
    }

    /**
     * 刷新项目数据
     * @return
     */
    @GetMapping("/refreshProject/{dayType}")
    public R<Map<String, Object>> refreshProject(@PathVariable String dayType) {
        Long channelId = SecurityUtils.getChannelId();
        // List<String> dateList = DateUtils.getDateListByDateType(dayType);
        String day = DateUtil.format(new Date(), DatePattern.NORM_DATE_FORMAT);
        Map<String, Object> projectData = new HashMap<>();

        for (ProjectEnum type : ProjectEnum.values()) {
            int count = projectService.selectProjectCount(new ProjectCountCriteria()
                    .setChannelId(channelId)
                    .setType(type.name())
                    .setDate(day));
            int money = projectCollectionService.sumProjectMoney(new ProjectCountCriteria()
                    .setChannelId(channelId)
                    .setType(type.name())
                    .setDate(day));
            projectData.put(type.name(), count);
            projectData.put(type.name()+"业绩", money);
        }
        projectData.put("Date", DateUtil.format(new Date(), DatePattern.NORM_DATETIME_MINUTE_FORMAT));
        return R.ok(projectData);
    }

    /**
     * 刷新客户数据
     * @return
     */
    @GetMapping("/refreshClient/{dayType}")
    public R<Map<String, Object>> refreshClient(@PathVariable String dayType) {
        Long userId = SecurityUtils.getUserId();

        String day = DateUtil.format(new Date(), DatePattern.NORM_DATE_FORMAT);
        Map<String, Object> clientData = new HashMap<>();

        for (ClientEnum type : ClientEnum.values()) {
            int count = clientService.selectClientCount(new ClientCountCriteria()
                    .setUserId(userId)
                    .setType(type.name())
                    .setDate(day));
            clientData.put(type.name(), count);
        }
        clientData.put("Date", DateUtil.format(new Date(), DatePattern.NORM_DATETIME_MINUTE_FORMAT));
        return R.ok(clientData);
    }


    /**
     * 刷新下级道数据
     * @return
     */
    @GetMapping("/refreshChannel/{dayType}")
    public R<Map<String, Object>> refreshChannel(@PathVariable String dayType) {
        Long channelId = SecurityUtils.getChannelId();
        String day = DateUtil.format(new Date(), DatePattern.NORM_DATE_FORMAT);
        Map<String, Object> channelData = new HashMap<>();
        channelData.put("下级渠道", channelService.selectChannelCount(new ChannelCountCriteria().setParentId(channelId).setDate(day)));
        channelData.put("Date", DateUtil.format(new Date(), DatePattern.NORM_DATETIME_MINUTE_FORMAT));
        return R.ok(channelData);
    }

    /**
     * 客户数据
     * @param userId
     * @param dateType
     * @return
     */
    private Map<String, Object> getClientData(Long userId, Long channelId, String dateType) {
        List<String> dateList = DateUtils.getDateListByDateType(dateType);
        if (dateList.isEmpty()) {
            return null;
        }

        Map<String, Object> clientData = new HashMap<String, Object>();

        if(dateType.equals("本月")){
            clientData.put("全部", clientService.selectClientCount(new ClientCountCriteria().setUserId(userId).setDate(dateList.get(0))));
        }
        if(dateType.equals("上月")){
            clientData.put("全部", clientService.selectClientCount(new ClientCountCriteria().setUserId(userId).setDate(dateList.get(0))));
        }
        for (ClientEnum type : ClientEnum.values()) {

            int count = statService.selectStatSum(new StatSumCriteria()
                    .setChannelId(channelId)
                    .setTimeList(dateList)
                    .setCode(type.name()));

            clientData.put(type.name(), count);
        }

        return clientData;
    }

    /**
     * 项目数据
     * @param channelId
     * @param dateType
     * @return
     */
    private Map<String, Object> getProjectData(Long channelId, String dateType) {
        List<String> dateList = DateUtils.getDateListByDateType(dateType);
        if (dateList.isEmpty()) {
            return null;
        }
        Map<String, Object> projectData = new HashMap<String, Object>();

        if(dateType.equals("本月")){
            projectData.put("全部", projectService.selectProjectCount(new ProjectCountCriteria().setChannelId(channelId).setDate(dateList.get(0))));
        }
        if(dateType.equals("上月")){
            projectData.put("全部", projectService.selectProjectCount(new ProjectCountCriteria().setChannelId(channelId).setDate(dateList.get(0))));
        }

        for (ProjectEnum type : ProjectEnum.values()) {
            int count = statService.selectStatSum(new StatSumCriteria()
                    .setChannelId(channelId)
                    .setTimeList(dateList)
                    .setCode(type.name()));

            projectData.put(type.name(), count);
        }
        return projectData;
    }



    /**
     * 收益数据
     * @param channelId
     * @param dateType
     * @return
     */
    private Map<String, Object> getProjectMoneyData(Long channelId, String dateType) {

        List<String> dateList = DateUtils.getDateListByDateType(dateType);
        if (dateList.isEmpty()) {
            return null;
        }
        Map<String, Object> projectMoneyData = new HashMap<String, Object>();

        if(dateType.equals("本月")){
            projectMoneyData.put("全部", projectCollectionService.sumProjectMoney(new ProjectCountCriteria().setChannelId(channelId).setDate(dateList.get(0))));
        }
        if(dateType.equals("上月")){
            projectMoneyData.put("全部", projectCollectionService.sumProjectMoney(new ProjectCountCriteria().setChannelId(channelId).setDate(dateList.get(0))));
        }

        for (ProjectEnum type : ProjectEnum.values()) {
            int count = statService.selectStatSum(new StatSumCriteria()
                    .setChannelId(channelId)
                    .setTimeList(dateList)
                    .setCode(type.name()+"业绩"));

            projectMoneyData.put(type.name()+ "业绩", count);
        }
        return projectMoneyData;


    }

    /**
     * 渠道数据
     * @param channelId     * @param dateType
     * @return
     */
    private Map<String, Object> getChannelData(Long channelId, String dateType) {
        Long userId = SecurityUtils.getUserId();
        List<String> dateList = DateUtils.getDateListByDateType(dateType);
        if (dateList.isEmpty()) {
            return null;
        }
        Map<String, Object> channelData = new HashMap<String, Object>();
        if(dateType.equals("本月")){
            channelData.put("全部", channelService.selectChannelCount(new ChannelCountCriteria().setParentId(channelId).setDate(dateList.get(0))));
        }
        if(dateType.equals("上月")){
            channelData.put("全部", channelService.selectChannelCount(new ChannelCountCriteria().setParentId(channelId).setDate(dateList.get(0))));
        }
        for (ChannelEnum type : ChannelEnum.values()) {
            int count = statService.selectStatSum(new StatSumCriteria()
                    .setChannelId(channelId)
                    .setTimeList(dateList)
                    .setCode(type.name()));
            channelData.put(type.name(), count);
        }
        return channelData;
    }


}
